package com.jlh.viewer.thread;

import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * @author mymx.jlh
 * @version 1.0.0 2018/4/21 14:05
 */
public class CompletionService {

    public static Random random = new Random(System.currentTimeMillis());
    public static void main(String[] args) {
        java.util.concurrent.CompletionService<String> completionService = new ExecutorCompletionService<>(Executors.newFixedThreadPool(3));
        int size =20;

        for (int i=0;i<size;i++){
            int finalI = i;
            completionService.submit(()->{
                Integer ram = random.nextInt()%1000;
                TimeUnit.MICROSECONDS.sleep(ram);
                return String.format("i=%s,ram=%s", finalI,ram);
            });
        }


        for (int i=0 ;i<size;i++){
            try {
                Future<String> future = completionService.take();
                System.out.println(future.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
}
